var util = require('../utils/commonUtil.js')

self.addEventListener('data_in', function (e) {
    handleProductList(e.data);
});
function handleProductList(data) {
    var timeStamps = [];
    for (var i = 0; i < data.products.length; i++) {
        var product = data.products[i];
        var temp = {};
        temp.startTime = product.startTime;
        temp.endTime = product.endTime;
        temp.state = product.productStatus;
        switch (product.productStatus) {
            case 2:
                temp.timeStr = util.endTimeToCountDownStr(timeStamps[i].endTime);
                break;
            case 1:
            case 3:
            case 4:
            default:
                temp.timeStr = util.timeToSpecialStr(timeStamps[i].startTime);
                break;
        }
        timeStamps.push(temp);
    }
    self.postMessage({"msg": "1", "content": timeStamps});
    startCountDown(timeStamps);
};

function startCountDown(timeStamps) {
    setInterval(function () {
        var that = this;
        for (var i = 0; i < timeStamps.length; i++) {
            if (timeStamps[i].state == 2) {
                timeStamps[i].timeStr = util.endTimeToCountDownStr(timeStamps[i].endTime);
                if (timeStamps[i].timeStr == "00:00:00") {
                    clearInterval(that);
                    self.postMessage({"msg": "2", "content": "reload"});
                }
            }
        }
        self.postMessage({"msg": "1", "content": timeStamps});
    }, 500);
};

module.exports = {
    startCountDown:startCountDown
};
